// src/stores/modules/device.js
import { defineStore } from 'pinia';
import AxiosMethods from '@/utils/AxiosMethods';
import { ElMessage } from 'element-plus'; // 引入 ElMessage 用于内部的提示

const DeviceStatusMap = {
  0: { label: '正常运行', tagType: 'success' },
  1: { label: '异常', tagType: 'danger' },
  2: { label: '停机维护', tagType: 'warning' },
};

export const useDeviceStore = defineStore('device', {
  state: () => ({
    deviceList: [],
    loading: false,
    total: 0,
    searchForm: {
      eqname: '',
      eqtype: '',
      eqstatus: null,
      eqmodel: null,
      eqmanufacture: '',
      pageNo: 1,
      pageSize: 10,
      sortBy: 'eqid',
      isAsc: true,
    },
    deviceForm: {
      eqid: null,
      eqname: '',
      eqtype: '',
      eqdiscribe: '',
      eqmodel: null,
      eqmanufacture: '',
      eqtime: '',
      eqcount: null,
      eqprice: null,
      eqv: null,
      eqa: null,
      eqw: null,
      eqstatus: 0,
    },
    selectedDevices: [],
    dialogVisible: false,
    isEdit: false,
    formSubmitting: false, 
    // 将 DeviceStatusMap 也暴露出去，方便其他组件获取状态映射
    DeviceStatusMap: DeviceStatusMap, 
  }),
  actions: {
    /**
     * 获取设备列表
     * @param {Object} params - 查询参数，会合并到 searchForm
     * @returns {Array} 返回获取到的设备记录数组，同时更新 store.deviceList 和 store.total
     */
    async fetchDeviceList(params = {}) {
      this.loading = true; // 开启 loading 状态
      try {
        const mergedParams = {
          ...this.searchForm, // 使用默认搜索表单
          ...params, // 传入的参数覆盖默认值
        };

        // 处理空字符串为 null，以便后端接收可选的数字字段
        for(const key of ['eqmodel', 'eqstatus']) {
            if (mergedParams[key] === '') {
                mergedParams[key] = null;
            }
        }
        // 如果外部传入 params.eqstatus 设置为 '异常', '正常运行' 等字符串，需要转换
        // 或者约定外部直接传入数字ID
        if (typeof mergedParams.eqstatus === 'string') {
          for (const key in DeviceStatusMap) {
            if (DeviceStatusMap[key].label === mergedParams.eqstatus) {
              mergedParams.eqstatus = parseInt(key); // 转换为数字ID
              break;
            }
          }
        }


        const response = await AxiosMethods.get('/eq', { params: mergedParams });

        if (response.data && response.data.code === true) {
          this.deviceList = response.data.data.records;
          this.total = response.data.data.total;
          return response.data.data.records; // 返回实际数据 records
        } else {
          console.error('Failed to fetch devices:', response.data.message || '获取设备列表失败');
          throw new Error(response.data.message || '获取设备列表失败');
        }
      } catch (error) {
        console.error('Error fetching devices:', error);
        throw error;
      } finally {
        this.loading = false; // 关闭 loading 状态
      }
    },

    /**
     * 获取单个设备详情
     * @param {number} id - 设备ID
     * @returns {Object} 返回单个设备对象
     */
    async fetchDeviceDetail(id) {
      try {
        const response = await AxiosMethods.get(`/eq/${id}`);
        if (response.data && response.data.code === true) {
          return response.data.data; // 返回单个设备对象
        } else {
          console.error('Failed to fetch device detail:', response.data.message || '获取设备详情失败');
          throw new Error(response.data.message || '获取设备详情失败');
        }
      } catch (error) {
        console.error('Error fetching device detail:', error);
        throw error;
      }
    },

    _prepareDeviceData(formData) {
      const dataToSend = { ...formData };

      const numberFields = ['eqmodel', 'eqcount', 'eqprice', 'eqv', 'eqa', 'eqw', 'eqstatus'];
      for (const key of numberFields) {
        let value = dataToSend[key];
        if (value === '' || value === undefined) {
          dataToSend[key] = null;
        } else if (typeof value === 'string') {
          const num = Number(value);
          dataToSend[key] = isNaN(num) ? null : num;
        }
      }

      if (dataToSend.eqtime) {
        if (typeof dataToSend.eqtime === 'string') {
          if (dataToSend.eqtime.length === 10 && !dataToSend.eqtime.includes('T')) {
            dataToSend.eqtime = `${dataToSend.eqtime}T00:00:00`;
          }
        }
      } else {
        dataToSend.eqtime = null;
      }

      const stringFields = ['eqname', 'eqtype', 'eqdiscribe', 'eqmanufacture'];
      for (const key of stringFields) {
        if (dataToSend[key] === '') {
          dataToSend[key] = null;
        }
      }

      return dataToSend;
    },

    async addDevice(device) {
      this.formSubmitting = true;
      try {
        const dataToSend = this._prepareDeviceData(device);
        const response = await AxiosMethods.post('/eq', dataToSend);
        if (response.data && response.data.code !== true) {
            throw new Error(response.data.message || '添加设备失败');
        }
        await this.fetchDeviceList(this.searchForm);
      } catch (error) {
        console.error('Error adding device:', error);
        throw error;
      } finally {
        this.formSubmitting = false;
      }
    },

    async updateDevice(device) {
      this.formSubmitting = true;
      try {
        const dataToSend = this._prepareDeviceData(device);
        const eqidForPath = dataToSend.eqid; 
        const response = await AxiosMethods.put(`/eq/${eqidForPath}`, dataToSend);
        if (response.data && response.data.code !== true) {
            throw new Error(response.data.message || '更新设备失败');
        }
        await this.fetchDeviceList(this.searchForm);
      } catch (error) {
        console.error('Error updating device:', error);
        throw error;
      } finally {
        this.formSubmitting = false;
      }
    },

    async deleteDevice(deviceId) {
      try {
        const response = await AxiosMethods.delete(`/eq/${deviceId}`);
        if (response.data && response.data.code !== true) {
            throw new Error(response.data.message || '删除设备失败');
        }
         ElMessage.success('删除成功');
        const currentPage = this.searchForm.pageNo;
        const totalItemsAfterDelete = this.total - 1;
        const maxPage = Math.max(1, Math.ceil(totalItemsAfterDelete / this.searchForm.pageSize));
        if (currentPage > maxPage) {
            this.searchForm.pageNo = maxPage;
        }
        await this.fetchDeviceList(this.searchForm); // 会更新 this.deviceList 和 this.total
        return true; 
      } catch (error) {
        console.error('Error deleting device:', error);
        ElMessage.error(`删除设备失败: ${error.message || '未知错误'}`);
        throw error;
      }
    },

    async deleteDevices(deviceIds) {
      if (!deviceIds || deviceIds.length === 0) {
        ElMessage.warning('请至少选择一个要删除的设备');
        return;
      }
      this.formSubmitting = true; 

      let successCount = 0;
      const failedDevices = [];
      const totalToDelete = deviceIds.length;

      try {
        const deletePromises = deviceIds.map(async (deviceId) => {
          try {
            const response = await AxiosMethods.delete(`/eq/${deviceId}`);
            if (response.data && response.data.code !== true) {
              throw new Error(response.data.message || `删除设备 ${deviceId} 失败`);
            }
            return { status: 'fulfilled', deviceId: deviceId };
          } catch (error) {
            return { status: 'rejected', deviceId: deviceId, reason: error.message || error };
          }
        });

        const results = await Promise.allSettled(deletePromises);

        results.forEach(result => {
          if (result.status === 'fulfilled') {
            successCount++;
          } else {
            failedDevices.push(result.deviceId);
            console.error(`删除设备 ${result.deviceId} 失败:`, result.reason);
          }
        });

        if (successCount === totalToDelete) {
          ElMessage.success(`成功删除了 ${successCount} 个设备。`);
        } else if (successCount > 0 && failedDevices.length > 0) {
          // 对失败的ID格式化展示
          const failedIdsMsg = failedDevices.length > 5 ? failedDevices.slice(0, 5).join(', ') + '...' : failedDevices.join(', ');
          ElMessage.warning(`部分设备删除成功：成功 ${successCount} 个，失败 ${failedDevices.length} 个（ID: ${failedIdsMsg}）。`);
        } else {
          ElMessage.error(`所有设备删除失败，请检查控制台详情。`);
        }
        
        const currentPage = this.searchForm.pageNo;
        const totalItemsAfterDeletion = this.total - successCount; 
        const maxPage = Math.max(1, Math.ceil(totalItemsAfterDeletion / this.searchForm.pageSize));
        if (currentPage > maxPage) {
            this.searchForm.pageNo = maxPage;
        }
        await this.fetchDeviceList(this.searchForm);
        this.selectedDevices = [];

      } catch (error) {
        console.error('批量删除操作出现未知错误:', error);
        ElMessage.error(`批量删除操作失败: ${error.message || '未知错误'}`);
      } finally {
        this.formSubmitting = false;
      }
    },

    resetSearchForm() {
      this.searchForm = {
        eqname: '',
        eqtype: '',
        eqstatus: null,
        eqmodel: null,
        eqmanufacture: '',
        pageNo: 1,
        pageSize: 10,
        sortBy: 'eqid',
        isAsc: true,
      };
      this.fetchDeviceList();
    },

    resetDeviceForm() {
      this.deviceForm = {
        eqid: null,
        eqname: '',
        eqtype: '',
        eqdiscribe: '',
        eqmodel: null,
        eqmanufacture: '',
        eqtime: '',
        eqcount: null,
        eqprice: null,
        eqv: null,
        eqa: null,
        eqw: null,
        eqstatus: 0,
      };
    },

    updateSelectedDevices(selectedDevices) {
      this.selectedDevices = selectedDevices;
    },

    // 这两个方法直接使用了 DeviceStatusMap，因此它们是通用的
    getStatusTagType(statusId) {
      return DeviceStatusMap[statusId] ? DeviceStatusMap[statusId].tagType : '';
    },

    getDeviceStatusLabel(statusId) {
      return DeviceStatusMap[statusId] ? DeviceStatusMap[statusId].label : '未知状态';
    },
  },
});
